package com.cos.blog.controller;

import com.cos.blog.listener.ThymeleafListener;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/PageServlet/*")
public class PageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、通过请求地址获取跳转的页面
        String path=request.getRequestURI().replaceAll("/PageServlet/","");
        // 直接转发过去发现thymeleaf的标签无法解析，所以这里需要用thymleaf的方式跳转
       //request.getRequestDispatcher("/WEB-INF/templates" + path).forward(request, response);

//    匹配.html后缀的文件   /templates/【】*.html/
        // uri:/PageServlet/system/index.html
        String page = path.replace(".html", "");
        System.out.println("page:"+page);

        // 2、获取上下文对象
        ServletContext servletContext = request.getServletContext();

        // 3.获取模板引擎对象
        TemplateEngine templateEngine = ThymeleafListener.getTemplateEngine(servletContext);

        // 4.创建一个WebContext对象
        WebContext webContext = new WebContext(request, response, servletContext);

        // 5.跳转到指定的页面(thymeleaf就会实现渲染)
        templateEngine.process(page, webContext, response.getWriter());
    }
}
